/**
 * 需求：添加商品，添加购物车功能
 * 1. 切片：    goods [商品切片] 、      cart [购物车切片]
 * 2. 数据：    goodsList[商拼列表]      cartList[购物车列表数据]
 * 3. reducer： addGoods 添加商品        addCart 添加购物车
 *              
 */
import { createSlice, configureStore } from '@reduxjs/toolkit'

// 创建商品切片
const goodsSlice = createSlice({
    name: 'goods',
    initialState: {
        goodsList: []
    },
    reducers: {
        addGoods(state, { payload }) {
            console.log('goods payload: ', payload);
            // 添加商品
            state.goodsList = [...state.goodsList, {
                id: Math.random().toString(36).slice(2),
                ...payload
            }]
        }
    }
})

// 购物车切片
const cartSlice = createSlice({
    name: 'cart',
    initialState: {
        cartList: []
    },
    reducers: {
        addCart(state, { payload }) {
            // 判断当前商品在 cartList中是否存在，如果存购买数量 + 1
            let index = state.cartList.findIndex(item => {
                return item.id === payload.id
            })
            if (index === -1) {
                // 不存在新增
                console.log('cart payload: ', payload)
                state.cartList.push({
                    ...payload,
                    buyNum: 1 // 购买数量1
                })
            }else{// 存在
                state.cartList[index].buyNum += 1
            }

        }
    }
})

// 创建数据仓库
const store = configureStore({
    reducer: {
        goods: goodsSlice.reducer,
        cart: cartSlice.reducer
    }
})
console.log(store.getState());

// 监听
store.subscribe(() => {
    console.log(store.getState());
})

// 导入actionCreator
const { addGoods } = goodsSlice.actions;
const { addCart } = cartSlice.actions;

// 添加商品
let goodsAction = addGoods({
    gname: '华为手机',
    price: 5980
})
console.log('goodsAction: ', goodsAction);
store.dispatch(goodsAction)
// 添加商品
store.dispatch(addGoods({
    gname: '小米手机',
    price: 3990
}))


// 添加购物车
let goods1 = store.getState().goods.goodsList[1]
store.dispatch(addCart(goods1))

let goods2 = store.getState().goods.goodsList[0]
store.dispatch(addCart(goods2))
store.dispatch(addCart(goods2))



